package com.chat.controller;

import com.alibaba.fastjson2.JSON;
import com.chat.dto.ChatDto;
import com.chat.entity.Users;
import com.chat.service.ChatService;
import com.chat.util.Util;
import com.chat.vo.ServerReturnVo;
import com.chat.vo.TokenVo;
import lombok.Data;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

//聊天功能使用
@RestController
@RequestMapping("chat")
@CrossOrigin

public class ChatController {
    @Autowired
    private ChatService chatService;
    @GetMapping("message")
    public String getMessages(@RequestHeader("token") String token){
        ServerReturnVo serverReturnVo=new ServerReturnVo(0,chatService.getMessages(token));
        return JSON.toJSONString(serverReturnVo);
    }
    @GetMapping("findUsers")
    public String findUsers(@RequestHeader("token") String token, @Param("username") String username){
        ServerReturnVo serverReturnVo=new ServerReturnVo(0,chatService.findUsers(token,username));
        if(serverReturnVo.data==null){
            serverReturnVo.code=500;
            serverReturnVo.data="无数据";
        }
        return JSON.toJSONString(serverReturnVo);
    }
    @PostMapping("send")
    public Boolean sendMessage(@RequestHeader("token") String token,@RequestBody Map<String,Object> map){
       try {
           System.out.println(map);
           Long id= Long.valueOf(map.get("id").toString()),uid=Long.valueOf(map.get("uid").toString());
           String message= (String) map.get("message");
           Boolean isSend=chatService.sendMessage(id,uid,message);
           if(isSend==true) {
               System.out.println(1);
               ChatDto.sendMessageTo(uid, JSON.toJSONString(map));
           }
           return isSend;
       }catch (Exception error){
           System.out.println(111);
           return false;
       }
//        ServerReturnVo serverReturnVo=new ServerReturnVo(0,chatService.getMessages(token));
//        return JSON.toJSONString(serverReturnVo);
    }
}
